package com.jason.basicandroid.service_client;

import com.jason.basicandroid.service.IAIDLService1;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AIDLService1Client extends Activity {
	protected static final String TAG = "AIDLService1Client"; 
	private IAIDLService1 stockService = null; 
	
	private Button btnBindService = null;
	private Button btnUnbindService = null;
	private Button btnCallService = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnBindService = (Button)findViewById(R.id.btnBindService);
        btnUnbindService = (Button)findViewById(R.id.btnUnbindService);
        btnCallService = (Button)findViewById(R.id.btnCallService);
    }
    
    public void bindService(View view) {
    	bindService(new Intent(IAIDLService1.class.getName()),
    			serConn, Context.BIND_AUTO_CREATE);
    	
    	btnBindService.setEnabled(false);
    	btnUnbindService.setEnabled(true);
    	btnCallService.setEnabled(true);
    }
    
    public void unbindService(View view) {
    	unbindService(serConn);

    	btnBindService.setEnabled(true);
    	btnUnbindService.setEnabled(false);
    	btnCallService.setEnabled(false);
    }
    
    public void callService(View view) {
    	try {
    		if(stockService != null) {
        		double val = stockService.getStockQuoter("Google");
        		Toast.makeText(AIDLService1Client.this,
        				"Value from service is " + val,  
        				 Toast.LENGTH_SHORT).show();
    		} else {
        		Toast.makeText(AIDLService1Client.this,
        				"Service is not registed!",  
        				 Toast.LENGTH_SHORT).show();
    		}
    	} catch(RemoteException e) {
    		e.printStackTrace();
    	}
    }
    
    private ServiceConnection serConn = new ServiceConnection() { 
 
        @Override 
        public void onServiceConnected(ComponentName name, IBinder service) 
        { 
            Log.v(TAG, "onServiceConnected() called"); 
            stockService = IAIDLService1.Stub.asInterface(service); 
        } 
 
        @Override 
        public void onServiceDisconnected(ComponentName name) { 
            Log.v(TAG, "onServiceDisconnected() called"); 
            stockService = null; 
        } 
    };
}